package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.AddressBookDTO;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> list() {
        Long userId = BaseContext.getCurrentId();
        return addressBookMapper.list(userId);
    }

    @Override
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.save(addressBook);
    }

    @Override
    public AddressBook detail(Long id) {
        return addressBookMapper.getById(id);
    }

    @Override
    public void removeById(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    @Override
    public AddressBook getDefault() {
        AddressBook addressBook = addressBookMapper.getDefault(BaseContext.getCurrentId());
        return addressBook;
    }

    @Override
    public void setDefault(Long id) {
        // 先将默认地址清空
        List<AddressBook> list = addressBookMapper.list(BaseContext.getCurrentId());
        for (AddressBook addressBook : list) {
            addressBook.setIsDefault(0);
            addressBookMapper.update(addressBook);
        }

        // 再设置默认地址
        AddressBook address = addressBookMapper.getById(id);
        address.setIsDefault(1);
        addressBookMapper.update(address);
    }
}
